package common

import (
	"fmt"
	"strings"

	"github.com/gorcon/rcon"
)

type Rcon struct {
	serv string
	psw  string
}

type Players struct {
	Name    string `json:"name"`
	UID     string `json:"uid"`
	SteamID string `json:"steamid"`
}

func NewRcon() *Rcon {
	info := GetInfo()
	conf := NewConfig()
	ip := info.Server
	port := conf.Get("RCONPort").(string)
	psw := conf.Get("AdminPassword").(string)
	serv := fmt.Sprintf("%s:%s", ip, port)

	return &Rcon{
		serv: serv,
		psw:  psw[1 : len(psw)-1],
	}
}

func (r *Rcon) Exec(cmd string) (string, error) {
	conn, err := rcon.Dial(r.serv, r.psw)

	if err != nil {
		return "", fmt.Errorf("rcon dail err: %s", err.Error())
	}

	defer conn.Close()

	str, err := conn.Execute(cmd)
	if err != nil {
		return "", fmt.Errorf("exec err: %s", err.Error())
	}
	return str, nil
}

func (r *Rcon) Save() (string, error) {
	return r.Exec("Save")
}

func (r *Rcon) BroadCast(msg string) string {
	msg = strings.ReplaceAll(msg, " ", "\t")
	str, _ := r.Exec(fmt.Sprintf("Broadcast %s", msg))
	return str
}

func (r *Rcon) ShutDown(t int, msg string) {
	msg = strings.ReplaceAll(msg, " ", "\t")
	r.Exec(fmt.Sprintf("Shutdown %d %s", t, msg))
}

func (r *Rcon) GetPlayers() ([]Players, error) {
	response, err := r.Exec("showplayers")
	if err != nil {
		return []Players{}, fmt.Errorf("get players err: %s", err.Error())
	}
	pls := strings.Split(response[23:], "\n")

	players := make([]Players, len(pls)-1)

	for i := 0; i < len(pls)-1; i++ {
		infs := strings.Split(pls[i], ",")
		players[i] = Players{
			Name:    infs[0],
			UID:     infs[1],
			SteamID: infs[2],
		}
	}

	return players, nil
}

func (r *Rcon) Ban(uid string) (string, error) {
	return r.Exec(fmt.Sprintf("banplayer %s", uid))
}
func (r *Rcon) Kick(uid string) (string, error) {
	return r.Exec(fmt.Sprintf("kickplayer %s", uid))
}
